<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加角色按钮 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table
        :data="roleList"
        style="width: 100%"
        :stripe="true"
        :border="true"
      >
        <!-- 展开权限表 -->
        <el-table-column type="expand" width="50">
          <template slot-scope="scope">
            <!-- 第一层 -->
            <el-row
              v-for="item1 in scope.row.children"
              :key="item1.id"
              class="border1"
            >
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="deleteRight(scope.row, item1)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 第二层与第三层 -->
              <el-col :span="19">
                <!-- 第二层 -->
                <el-row
                  v-for="item2 in item1.children"
                  :key="item2.id"
                  class="border2"
                >
                  <el-col :span="6">
                    <el-tag closable @close="deleteRight(scope.row, item2)">{{
                      item2.authName
                    }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="deleteRight(scope.row, item3)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
                <!-- 第二层 -->
              </el-col>
              <!-- 第二层与第三层 -->
            </el-row>
            <!-- 第一层 -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteRole(scope.row)"
              >删除</el-button
            >
            <el-button type="warning" @click="showSetDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="closeAddDialog"
    >
      <el-form ref="roleFormRef" :model="roleForm" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="closeEditDialog"
    >
      <el-form ref="editFormRef" :model="editRoleForm" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="closeSetRightDialog"
    >
      <el-tree
        :data="rightList"
        :props="rightTreeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="rightKey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      editRoleForm: {},
      // 添加角色表单双向绑定，用于发送请求的数据
      roleForm: {
        roleName: '主管1',
        roleDesc: '超级大牛'
      },
      // 获取的角色列表
      roleList: [],
      // 获取的整个权限列表，用于权限分配
      rightList: [],
      rightKey: [],
      roleID: '',
      // 权限树的指定属性
      rightTreeProps: {
        label: 'authName',
        children: 'children'
      },
      // 添加角色的检验，不加点取消没法清空
      addRules: {
        roleName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleList = res.data
    },
    // 关闭清空
    closeAddDialog() {
      this.$refs.roleFormRef.resetFields()
    },
    closeEditDialog() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加角色按钮函数
    async addRole() {
      const { data: res } = await this.$http.post('roles', this.roleForm)
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.addDialogVisible = false
      this.getRoleList()
    },
    // 用id查询角色信息
    async showEditDialog(state) {
      const { data: res } = await this.$http.get(`roles/${state.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editDialogVisible = true
      this.editRoleForm = res.data
    },
    // 编辑角色信息并修改数据库
    editRole() {
      this.$refs.editFormRef.validate(async val => {
        if (val) {
          const { data: res } = await this.$http.put(
            `roles/${this.editRoleForm.roleId}`,
            {
              roleName: this.editRoleForm.roleName,
              roleDesc: this.editRoleForm.roleDesc
            }
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.editDialogVisible = false
          this.getRoleList()
        }
      })
    },
    // 删除角色
    deleteRole(state) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async res => {
          const { data: response } = await this.$http.delete(
            `roles/${state.id}`
          )
          if (response.meta.status !== 200) {
            return this.$message.error(response.meta.msg)
          }
          this.$message.success(response.meta.msg)
          this.getRoleList()
        })
        .catch(rea => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async deleteRight(state, item3) {
      const result = await this.$confirm('是否删除此权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${state.id}/rights/${item3.id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      state.children = res.data
    },
    // 显示对话框，获取权限数据
    async showSetDialog(role) {
      this.roleID = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rightList = res.data
      this.getRightTreeID(role, this.rightKey)
      this.setRightDialogVisible = true
    },
    // 获取三级节点的ID
    getRightTreeID(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getRightTreeID(item, arr)
      })
    },
    // 关闭分配权限对话框时，重置权限ID数组
    closeSetRightDialog() {
      this.rightKey = []
    },
    // 分配权限确定按钮
    // 先获取打了勾的权限ID，和半选权限ID，组成数组
    // 发送角色授权请求，需要权限ID列表
    async setRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleID}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  },
  created() {
    this.getRoleList()
  }
}
</script>

<style lang="less" scoped>
.border1 {
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}
.border1:nth-of-type(1) {
  border-top: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.border2 {
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}
.border2:last-of-type {
  border-bottom: none;
}
</style>
